package com.example.music_player

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.widget.Button
import android.widget.ImageButton
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

// PlayerActivity: 音乐播放器的详细播放界面，提供完整的播放控制功能
class PlayerActivity : AppCompatActivity(), MusicService.OnPlaybackStateChangeListener {
    // 界面组件
    private lateinit var tvPlayingSong: TextView        // 当前播放歌曲名称
    private lateinit var seekBar: SeekBar              // 进度条
    private lateinit var tvCurrentTime: TextView       // 当前播放时间
    private lateinit var tvTotalTime: TextView         // 总时长
    private lateinit var playPauseButton: ImageButton  // 播放/暂停按钮
    private lateinit var nextButton: ImageButton       // 下一首按钮
    private lateinit var previousButton: ImageButton   // 上一首按钮
    private lateinit var playModeButton: ImageButton   // 播放模式按钮
    
    private var musicService: MusicService? = null     // 音乐服务
    private var bound = false                          // 服务绑定状态

    private var isTracking = false                     // 是否正在手动调节进度条
    private val handler = Handler(Looper.getMainLooper())
    
    // 添加防抖变量
    private var lastClickTime = 0L
    private val CLICK_INTERVAL = 300L  // 点击间隔时间（毫秒）

    // 进度条更新任务
    private val updateSeekBar = object : Runnable {
        override fun run() {
            if (!isTracking && bound) {
                musicService?.let { service ->
                    val currentPosition = service.getCurrentPosition()
                    val duration = service.getDuration()
                    seekBar.max = duration
                    seekBar.progress = currentPosition
                    updateTimeText(currentPosition, duration)
                }
            }
            handler.postDelayed(this, 1000)  // 每秒更新一次
        }
    }

    // 服务连接回调
    private val connection = object : ServiceConnection {
        // 服务连接成功
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val binder = service as MusicService.MusicBinder
            musicService = binder.getService()
            bound = true
            musicService?.addPlaybackStateChangeListener(this@PlayerActivity)
            updatePlayingInfo()
        }

        // 服务断开连接
        override fun onServiceDisconnected(name: ComponentName?) {
            musicService?.removePlaybackStateChangeListener(this@PlayerActivity)
            musicService = null
            bound = false
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_player)

        // 初始化界面组件
        initializeViews()
        
        // 设置跑马灯效果
        tvPlayingSong.isSelected = true
        tvPlayingSong.requestFocus()

        // 绑定音乐服务
        Intent(this, MusicService::class.java).also { intent ->
            bindService(intent, connection, Context.BIND_AUTO_CREATE)
        }

        // 初始化播放模式图标
        initializePlayModeIcon()

        // 设置按钮点击事件
        setupButtonClickListeners()

        // 设置进度条监听器
        setupSeekBarListener()

        // 启动进度条更新
        handler.post(updateSeekBar)
    }

    // 初始化界面组件
    private fun initializeViews() {
        tvPlayingSong = findViewById(R.id.tv_playing_song)
        seekBar = findViewById(R.id.seek_bar)
        tvCurrentTime = findViewById(R.id.tv_current_time)
        tvTotalTime = findViewById(R.id.tv_total_time)
        playPauseButton = findViewById(R.id.btn_play_pause)
        nextButton = findViewById(R.id.btn_next)
        previousButton = findViewById(R.id.btn_previous)
        playModeButton = findViewById(R.id.btn_play_mode)
    }

    // 初始���播放模式图标
    private fun initializePlayModeIcon() {
        musicService?.let { service ->
            updatePlayModeIcon(service.getPlayMode())
        }
    }

    // 更新播放模式图标
    private fun updatePlayModeIcon(mode: MusicService.PlayMode) {
        when (mode) {
            MusicService.PlayMode.SEQUENTIAL -> playModeButton.setImageResource(R.drawable.ic_repeat)
            MusicService.PlayMode.SHUFFLE -> playModeButton.setImageResource(R.drawable.ic_shuffle)
            MusicService.PlayMode.REPEAT_ONE -> playModeButton.setImageResource(R.drawable.ic_repeat_one)
        }
    }

    // 设置按钮点击事件
    private fun setupButtonClickListeners() {
        // 播放/暂停按钮点击事件
        playPauseButton.setOnClickListener {
            if (musicService?.isPlaying() == true) {
                musicService?.pauseMusic()
                playPauseButton.setImageResource(R.drawable.ic_play)
            } else {
                musicService?.resumeMusic()
                playPauseButton.setImageResource(R.drawable.ic_pause)
            }
        }

        // 下一首按钮点击事件
        nextButton.setOnClickListener {
            if (isClickValid()) {  // 添加点击防抖检查
                musicService?.playNext()
                updatePlayingInfo()
            }
        }

        // 上一首按钮点击事件
        previousButton.setOnClickListener {
            if (isClickValid()) {  // 添加点击防抖检查
                musicService?.playPrevious()
                updatePlayingInfo()
            }
        }

        // 播放模式按钮点击事件
        playModeButton.setOnClickListener {
            when (musicService?.getPlayMode()) {
                MusicService.PlayMode.SEQUENTIAL -> {
                    musicService?.setPlayMode(MusicService.PlayMode.SHUFFLE)
                    playModeButton.setImageResource(R.drawable.ic_shuffle)
                }
                MusicService.PlayMode.SHUFFLE -> {
                    musicService?.setPlayMode(MusicService.PlayMode.REPEAT_ONE)
                    playModeButton.setImageResource(R.drawable.ic_repeat_one)
                }
                MusicService.PlayMode.REPEAT_ONE -> {
                    musicService?.setPlayMode(MusicService.PlayMode.SEQUENTIAL)
                    playModeButton.setImageResource(R.drawable.ic_repeat)
                }
                else -> {
                    musicService?.setPlayMode(MusicService.PlayMode.SEQUENTIAL)
                    playModeButton.setImageResource(R.drawable.ic_repeat)
                }
            }
        }
    }

    // 设置进度条监听器
    private fun setupSeekBarListener() {
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    updateTimeText(progress, seekBar?.max ?: 0)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                isTracking = true
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                isTracking = false
                seekBar?.let {
                    musicService?.seekTo(it.progress)
                }
            }
        })
    }

    // 更新时间显示
    private fun updateTimeText(currentPosition: Int, duration: Int) {
        tvCurrentTime.text = formatTime(currentPosition)
        tvTotalTime.text = formatTime(duration)
    }

    // 格式化时间（毫秒转换为 mm:ss 格式）
    private fun formatTime(timeMs: Int): String {
        val totalSeconds = timeMs / 1000
        val minutes = totalSeconds / 60
        val seconds = totalSeconds % 60
        return String.format("%02d:%02d", minutes, seconds)
    }

    // 更新播放信息
    private fun updatePlayingInfo() {
        musicService?.let { service ->
            // 更新歌曲名称
            service.getCurrentSongName()?.let { songName ->
                tvPlayingSong.text = songName
            }
            // 更新播放状态图标
            playPauseButton.setImageResource(
                if (service.isPlaying()) R.drawable.ic_pause else R.drawable.ic_play
            )
            // 更新进度条和时间显示
            val currentPosition = service.getCurrentPosition()
            val duration = service.getDuration()
            seekBar.max = duration
            seekBar.progress = currentPosition
            updateTimeText(currentPosition, duration)

            // 更新播放模式图标
            updatePlayModeIcon(service.getPlayMode())
        }
    }

    // 播放状态回调实现
    override fun onSongChanged(songName: String?) {
        tvPlayingSong.text = songName ?: "暂无播放"
    }

    override fun onPlayStateChanged(isPlaying: Boolean) {
        playPauseButton.setImageResource(
            if (isPlaying) R.drawable.ic_pause else R.drawable.ic_play
        )
    }

    // 资源清理
    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacks(updateSeekBar)
        musicService?.removePlaybackStateChangeListener(this)
        if (bound) {
            unbindService(connection)
            bound = false
        }
    }

    // 添加防抖检查方法
    private fun isClickValid(): Boolean {
        val currentTime = System.currentTimeMillis()
        val isValid = currentTime - lastClickTime > CLICK_INTERVAL
        if (isValid) {
            lastClickTime = currentTime
        }
        return isValid
    }
} 